﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CRMSystemV2.MVCWeb.Controllers
{
    public class FileController : Controller
    {
        //下载文件的零时目录
        public static readonly string DownloadPath = string.Format("{0}upload/temp/", AppDomain.CurrentDomain.BaseDirectory);
        //
        // GET: /File/文件下载，并删除源文件
        //
        public FileResult Download(string file)
        {
            string filePath = string.Format("{0}/{1}", DownloadPath, file);
            if (System.IO.File.Exists(filePath))
            {                
                string[] arr = file.Split('.');
                string contentType = GetContentType(arr[arr.Length - 1]);
                byte[] fileData = System.IO.File.ReadAllBytes(filePath);
                System.IO.File.Delete(filePath);
                return File(fileData, "application/ms-excel", file);
            }
            return null;
        }
        /// <summary>
        /// 通过文件后缀获取ContentType
        /// </summary>
        /// <param name="extension"></param>
        /// <returns></returns>
        private string GetContentType(string extension)
        {
            switch (extension.ToLower())
            {
                case "xls":
                    return "application/ms-excel";
                case "zip":
                    return "application/x-zip-compressed";
                default:
                    return "";
            }
        }
    }    
}
